navigation-utils.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { isPermalink } from '@growi/core/dist/utils/page-path-utils';
  2. import { removeHeadingSlash } from '@growi/core/dist/utils/path-utils';
  3. import type { Props, InitialProps, SameRouteEachProps } from './types';
  4. /**
  5. * Extract pageId from pathname efficiently
  6. * Returns null for non-permalink paths to optimize conditional checks
  7. */
  8. export const extractPageIdFromPathname = (pathname: string): string | null => {
  9. return isPermalink(pathname) ? removeHeadingSlash(pathname) : null;
  10. };
  11. /**
  12. * Type guard to check if props are initial props
  13. * Returns true if props contain initial data from SSR
  14. */
  15. export const isInitialProps = (props: Props): props is (InitialProps & SameRouteEachProps) => {
  16. return 'isNextjsRoutingTypeInitial' in props && props.isNextjsRoutingTypeInitial;
  17. };
  18. /**
  19. * Determines if page data should be fetched based on current state
  20. * Pure function with no side effects for better testability
  21. */
  22. export interface ShouldFetchPageParams {
  23. targetPageId: string | null;
  24. targetPathname: string;
  25. currentPageId?: string | null;
  26. currentPagePath?: string | null;
  27. }
  28. export const shouldFetchPage = (params: ShouldFetchPageParams): boolean => {
  29. const {
  30. currentPagePath, targetPageId, currentPageId, targetPathname,
  31. } = params;
  32. // Always fetch if:
  33. // 1. No current page data
  34. // 2. Different page ID (only if both are defined)
  35. // 3. Different path
  36. return (
  37. !currentPagePath // No current page
  38. || (targetPageId != null && currentPageId != null && currentPageId !== targetPageId) // Different page ID (strict comparison)
  39. || (currentPagePath !== targetPathname) // Different path
  40. );
  41. };